package com.mlamp.其他;

public class 只出现一次的数字 {

    public static void main(String[] args) {
        只出现一次的数字 instance = new 只出现一次的数字();
        int i = instance.singleNumber(new int[]{
                2, 2, 1
        });
        System.out.println(i);
        int i1 = instance.singleNumber(new int[]{
                4, 1, 2, 1, 2
        });
        System.out.println(i1);


        int i2[] = new int[]{
                4, 1, 2, 1, 2
        };
        try {
            System.out.println(onlyOneNumber(i2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public int singleNumberA(int[] nums) {
        assert nums != null : "nums is null";
        assert nums.length > 0 : "nums is empty";
        int num = 0;
        for (int i = 0; i < nums.length; i++) {
            num ^= nums[i];
        }
        return num;
    }


    public int singleNumber(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
        if (nums.length == 1) return nums[0];
        int num = 0;
        for (int i = 0; i < nums.length; i++) {
            num ^= nums[i];
        }
        return num;
    }

    public int singleNumA(int[] nums) {
        if (nums == null || nums.length == 0) throw new IllegalArgumentException("invalid nums");
        if (nums.length == 1) return nums[0];
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res ^= nums[i];
        }
        return res;
    }


    public Integer singleNum(int[] nums) {
        if (nums == null || nums.length == 0) return null;
        if (nums.length == 1) return nums[0];
        int num = 0;
        for (int i = 0; i < nums.length; i++) {
            num ^= nums[i];
        }
        return num;
    }


    public static int onlyOneNumber(int nums[]) throws Exception {
        if (nums == null || nums.length == 0) throw new Exception("invalid input");
        int theOne = 0;
        for (int i = 0; i < nums.length; i++) {
            theOne = theOne ^ nums[i];
        }
        return theOne;
    }


}
